package com.frogs.ucenter.openplatform.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.frogs.framework.util.PropertyUtil;
import com.frogs.framework.util.date.DateUtil;
import com.zhongan.openapi.security.signature.SignatureUtils;

public class ZhonganHttpsConnectUtil {
	
	private final static Logger log = LoggerFactory.getLogger(ZhonganHttpsConnectUtil.class);
	/**
     * 开发者的私钥
     */
    private static String devPrivateKey;

    /**
     * 众安的公钥
     */
    private static String zaPublicKey;

    /**
     * 开发者appkey
     */
    private static String appkey;
    
    private static String propertiesFileName = "insurance/zhonganopenplatform";
    /**
     * 网关url
     */
    private static String url;

    //private SimpleDateFormat sdf = new SimpleDateFormat("");
    
    static{
    	devPrivateKey = PropertyUtil.getProperty(propertiesFileName, "devPrivateKey");
    	zaPublicKey = PropertyUtil.getProperty(propertiesFileName, "zaPublicKey");
    	appkey = PropertyUtil.getProperty(propertiesFileName, "appkey");
    	url = PropertyUtil.getProperty(propertiesFileName, "url");
	}
    public static JSONObject post(String serviceName, Map<String, Object> map) throws Exception {
        HttpPost request = new HttpPost(url);

        //系统级别参数
        map.put("appKey", appkey);
        map.put("charset", "UTF-8");
        map.put("serviceName", serviceName);
        map.put("signType", "RSA");
        map.put("format", "json");
        map.put("version", "1.0.0");
        map.put("timestamp", DateUtil.formatDate(new Date(), "yyyyMMddHHmmssSSS"));
        //应用级别参数 从外层传进来
        //map.put("userName", "tester");
        //map.put("identityNo", "1234567890");
        //使用sdk util方法 加密 加签
        log.info("func[post] partner insurance params[{}]", new Object[] {JSON.toJSONString(map)});
        Map<String, Object> resultMap = SignatureUtils.encryptAndSign(map, zaPublicKey, devPrivateKey, "utf-8", true,
                true);
        //转换为NameValuePair 
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("sign", (String) resultMap.get("sign")));
        params.add(new BasicNameValuePair("timestamp", (String) resultMap.get("timestamp")));
        params.add(new BasicNameValuePair("bizContent", (String) resultMap.get("bizContent")));
        params.add(new BasicNameValuePair("signType", (String) resultMap.get("signType")));
        params.add(new BasicNameValuePair("charset", (String) resultMap.get("charset")));
        params.add(new BasicNameValuePair("appKey", (String) resultMap.get("appKey")));
        params.add(new BasicNameValuePair("serviceName", (String) resultMap.get("serviceName")));
        params.add(new BasicNameValuePair("format", (String) resultMap.get("format")));
        params.add(new BasicNameValuePair("version", (String) resultMap.get("version")));

        request.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
        HttpClient client = new DefaultHttpClient();
        //使用http调用请求
        HttpResponse response = client.execute(request);
        HttpEntity responseEntity = response.getEntity();
        //获取返回json字符串
        InputStream inputStream = responseEntity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder sb = new StringBuilder();
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
        	log.error("func[post] serviceName[{}] map[{}] exception[{} - {}] desc[fail]",//
					new Object[] {serviceName, JSON.toJSONString(map) , e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
        }
        JSONObject responseJson = JSONObject.parseObject(sb.toString());
        //如果bizContent为空 就不用解密了
        boolean isDecrypt = StringUtils.isEmpty(responseJson.getString("bizContent")) ? false : true;
        String responseBizContent = SignatureUtils.checkSignAndDecrypt(responseJson, zaPublicKey, devPrivateKey, true,
                isDecrypt);
        //bizContent为空
        if (StringUtils.isEmpty(responseBizContent)) {
            responseJson.put("bizContent", "");
        }
        //bizContent以[开头 是json数组
        else if (responseBizContent.startsWith("[")) {
            responseJson.put("bizContent", JSONArray.parseArray(responseBizContent));
        }
        //bizContent是 jsonObject
        else {
            responseJson.put("bizContent", JSONObject.parseObject(responseBizContent));
        }
        log.info("func[post] partner insurance result[{}]", new Object[] {JSON.toJSONString(responseJson)});
        return responseJson;

    }
    
    /**
     * 当事人新增接口
     * 
     * @param map(userName,sex,email,mobilePhone,identityNo,channelId,channelUserNo)
     * @return
     * @throws Exception
     */
    public static JSONObject addByChannel(Map<String, Object> map) throws Exception {
    	String serviceName = "zhongan.user.person.addByChannel";
    	return post(serviceName, map);
    }
    
    /**
     * 投保接口
     * 
     * @param map(policyHolderUserId,insuredUserId,beneficiaryUserId,channelOrderNo,premium,
     *		policyBeginDate,policyEndDate,insureDate,payType,channelId,productId,extraInfo)
     * @return
     * @throws Exception
     */
    public static JSONObject addPolicy(Map<String, Object> map) throws Exception {
    	String serviceName = "zhongan.policy.policy.add";
    	return post(serviceName, map);
    }
    
    /**
     * 退保接口
     * 
     * @param map(policyNo,channelId,productId)
     * @return
     * @throws Exception
     */
    public static JSONObject quitPolicy(Map<String, Object> map) throws Exception {
    	String serviceName = "zhongan.policy.policy.quit";
    	return post(serviceName, map);
    }
    
}